package cn.com.utt.unms.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.com.utt.common.alipay.config.AlipayConfig;
import cn.com.utt.common.alipay.util.AlipaySubmit;
import cn.com.utt.common.alipay.util.UtilDate;
import cn.com.utt.common.exception.BusinessException;
import cn.com.utt.common.mapper.UserMapper;
import cn.com.utt.common.vo.TableInput;
import cn.com.utt.common.vo.TableOutput;
import cn.com.utt.common.vo.User;
import cn.com.utt.unms.mapper.AuthSmsMapper;
import cn.com.utt.unms.mapper.OrderMapper;
import cn.com.utt.unms.mapper.SmsBuyMapper;
import cn.com.utt.unms.pojo.Order;
import cn.com.utt.unms.pojo.Product;
import cn.com.utt.unms.service.OrderService;
import cn.com.utt.unms.vo.OrderItem;

@Service("orderService")
public class OrderServiceImpl implements OrderService {

	@Autowired
	private SmsBuyMapper smsBuyMapper;

	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private AuthSmsMapper authSmsMapper;

	@Override
	@Transactional
	public String createSmsOrder(long userId, long productId, int num) {
		Product product = smsBuyMapper.queryProductById(productId);
		if (product == null) {
			return null;
		} else {
			double price = product.getPrice();
			double total = price * num;
			Order order = new Order();
			long cur = System.currentTimeMillis();
			String orderNo = UtilDate.getOrderNo();
			order.setOrderId(orderNo);
			order.setUserId(userId);
			order.setProductId(productId);
			order.setNum(num);
			order.setPrice(price);
			Timestamp stamp = new Timestamp(cur);
			order.setOrderTime(stamp);
			order.setPayMethod((byte) 1);
			order.setTotalFee(total);
			order.setPayStatus((byte) 0);
			orderMapper.save(order);
			return orderNo;
		}
	}

	@Override
	@Transactional
	public String payOrder(String orderNum) {
		Order order = orderMapper.queryOrder(orderNum);
		Product product = smsBuyMapper.queryProductById(order.getProductId());
		if (order != null && product != null) {
			String payment_type = "1";
			String notify_url = "http://47.97.110.84/v1/smsBuy/payNotify";
			String return_url = "http://47.97.110.84/v1/smsBuy/payReturn";
			String seller_email = "aitaiwangluo@utt.com.cn";
			String out_trade_no = order.getOrderId();
			String subject = product.getName();
			String total_fee = order.getTotalFee() + "";
			String body = "";
			String show_url = "";
			String anti_phishing_key = "";
			String exter_invoke_ip = "";
			// 把请求参数打包成数组
			Map<String, String> sParaTemp = new HashMap<String, String>();
			sParaTemp.put("service", "create_direct_pay_by_user");
			sParaTemp.put("partner", AlipayConfig.partner);
			sParaTemp.put("_input_charset", AlipayConfig.input_charset);
			sParaTemp.put("payment_type", payment_type);
			sParaTemp.put("notify_url", notify_url);
			sParaTemp.put("return_url", return_url);
			sParaTemp.put("seller_email", seller_email);
			sParaTemp.put("out_trade_no", out_trade_no);
			sParaTemp.put("subject", subject);
			sParaTemp.put("total_fee", total_fee);
			sParaTemp.put("body", body);
			sParaTemp.put("show_url", show_url);
			sParaTemp.put("anti_phishing_key", anti_phishing_key);
			sParaTemp.put("exter_invoke_ip", exter_invoke_ip);

			// 建立请求
			String sHtmlText = AlipaySubmit.buildRequest(sParaTemp, "get", "确认", false);
			return sHtmlText;
		}
		return null;
	}

	@Override
	@Transactional
	public void dealOrder(String orderNo, String tradeNo, String payAccount) throws BusinessException {
		// 根据orderNum查询订单状态
		Order order = orderMapper.queryOrder(orderNo);
		if (order != null) {
			if (order.getPayStatus() == 0) {
				// 订单状态处于没有处理状态的用户需要修改状态
				order.setPayStatus((byte) 1);
				Timestamp cur = new Timestamp(System.currentTimeMillis());
				order.setPayTime(cur);
				order.setPayAccount(payAccount);
				order.setTradeNo(tradeNo);
				// 修改订单状态
				try {
					orderMapper.updateOrder(order);
					// 如果商品id为1用户短信容量增加
					if (order.getProductId() == 1) {
						User user = userMapper.queryById(order.getUserId());
						if (user != null) {
							user.setSmsVolume(user.getSmsVolume() + order.getNum());
							userMapper.update(user);
						}
					} else {
						// id为2表示是认证短信
						authSmsMapper.addNum(order.getUserId(), order.getNum());
					}

				} catch (DataAccessException e) {
					throw new BusinessException(e.getMessage(), e);
				}
			} else if (order.getPayStatus() == 1) {
				// 已经支付过，直接返回已支付
			}

		}

	}

	@Override
	public TableOutput<OrderItem> queryByCondition(TableInput input, long userId) {

		Map<String, Object> conditions = new HashMap<>();
		conditions.put("searchs", input.getSearch());
		conditions.put("userId", userId);
		System.out.println(input);
		System.out.println(input.getOrder());
		if (input.getOrder() != null) {
			conditions.put("orderColumn", input.getOrder().getColumn());
			conditions.put("orderDirection", input.getOrder().getDir());
		}
		conditions.put("start", input.getStart());
		conditions.put("rows", input.getRows());
		int total = orderMapper.countByCondition(conditions);
		List<Order> orders = orderMapper.queryByCondition(conditions);
		System.out.println("total:" + total);

		List<OrderItem> orderItems = new ArrayList<>();

		if (orders != null) {
			for (Order order : orders) {
				OrderItem item = new OrderItem();
				item.setOrderId(order.getOrderId());
				item.setNum(order.getNum());
				item.setOrderTime(order.getOrderTime());
				if (order.getPayMethod() == 1) {
					item.setPayMethod("支付宝");
				} else {
					item.setPayMethod("优惠券");
				}
				item.setPayStatus(order.getPayStatus());
				item.setTotalFee(order.getTotalFee());
				if (order.getProductId() == 1) {
					item.setProduct("营销短信");
				} else {
					item.setProduct("认证短信");
				}
				orderItems.add(item);
			}
		}

		TableOutput<OrderItem> output = new TableOutput<>();
		output.setTotal(total);
		output.setRows(input.getRows());
		output.setStart(input.getStart());
		output.setList(orderItems);
		return output;
	}

}
